<template>
  <view class="container">
    <my-navbar-top></my-navbar-top>
    <view class="settlement-page">
      <!-- 选择地址 -->
      <view class="address-container" @click="handleAddAddress">
        <view v-if="currentAddress.id" class="address-item">
          <view class="title">配送地址</view>
          <view class="name">
            {{ currentAddress.realname }} {{ currentAddress.telephone }}
          </view>
          <view class="address">
            {{ currentAddress.province }} {{ currentAddress.city }}
            {{ currentAddress.area }} {{ currentAddress.address }}
          </view>
        </view>
        <view v-else class="address-item">
          <view class="title">配送地址</view>
          <view class="address-item-left">
            <view class="address-item-left-name">前往添加您的配送地址</view>
          </view>
        </view>
        <view class="add">添加地址</view>
      </view>
      <!-- 商品信息 -->
      <view class="goods-container">
        <view class="title">商品信息</view>
        <view class="goods-list">
          <order-item v-for="item in goodsList" :key="item.id" :item="item" />
        </view>
        <view class="other">
          <view class="other-item">
            <view class="other-item-title">小计</view>
            <view class="other-item-price">￥{{ small_price }}</view>
          </view>
          <view class="other-item">
            <view class="other-item-title">运费</view>
            <view class="other-item-price">￥{{ run_price }}</view>
          </view>
          <view class="other-line"> </view>
          <view class="remark">
            <view class="remark-title">备注</view>
            <view class="remark-input">
              <input
                v-model="remark"
                maxlength="10"
                type="text"
                placeholder-style="color: #979797;font-size: 23rpx;"
                placeholder="请输入您的备注信息（10个字以内）"
              />
            </view>
          </view>
          <view class="other-line"> </view>
          <view class="other-item" style="height: auto">
            <view class="other-item-title">总计</view>
            <view class="other-item-price">
              <view class="left">￥{{ total_price }}</view>
              <view class="right">
                <view class="button" @click="handlePay"> 立即支付 </view>
                <view class="tips"> * 特价商品非质量问题不退不换 </view>
              </view>
            </view>
          </view>
          <view style="height: 30rpx"></view>
        </view>
      </view>
    </view>
	<!-- 库存不足 默认弹框 -->
	<stock-popup ref="stockPopup" @close="getCarList"></stock-popup>
	<!-- 限购弹框 需要传入文案 -->
	<stock-popup ref="limitPopup" text1="您已超过今日最大购买限额" text2="请理性消费" @close="limitClose"></stock-popup>
	
	
  </view>
</template>

<script>
import orderItem from '@/components/goods/orderItem.vue'
import stockPopup from '@/components/stockPopup.vue'
export default {
  name: 'settlement',
  components: {
    orderItem,
    stockPopup,
  },
  data() {
    return {
      car_ids: '',
      product_id: '',
      buy_number: '',
      order_id: '',
      user_address_id: '',
      remark: '',
      run_price: 0, // 运费
      small_price: 0, // 小计
      total_price: 0, // 总价
      goodsList: [],
      currentAddress: {},
    }
  },
  onLoad(e) {
    // ids 或者 id+num
    if (e.ids || (e.id && e.num)) {
      this.getOrderInfo(e)
      this.car_ids = e.ids || ''
      this.product_id = e.id || ''
      this.buy_number = e.num || ''
      this.order_id = e.order_id || ''

      // 获取用户地址
      this.getAddress()
    }
  },
  onShow() {
    this.currentAddress = uni.getStorageSync('currentAddress') || {}
  },
  methods: {
    getAddress() {
      this.$api.getAddressList().then((res) => {
        console.log(res, 'res')
        let { user_address } = res.data
        let state = uni.getStorageSync('currentAddress') || null
        if (user_address && user_address.length > 0 && !state) {
          this.currentAddress =
            user_address.find((item) => item.is_default == 1) || {}
        }
        // 判断缓存的地址是否不在列表中
        if (state && !user_address.find((item) => item.id == state.id)) {
          uni.removeStorageSync('currentAddress')
          this.currentAddress = {}
        }
      })
    },
    getOrderInfo(e) {
      let o = {
        car_ids: e.ids || '',
        product_id: e.id || '',
        buy_number: e.num || '',
      }
      this.$api.orderInfo(o).then((res) => {
        console.log(res)
        if (res.code == 0) {
          this.goodsList = res.data || []
          this.run_price = res.run_price
          this.small_price = res.small_price
          this.total_price = res.total_price
        }
      })
    },
    handleAddAddress() {
      uni.navigateTo({
        url: '/pages/user/address/index?type=select',
      })
    },
	limitClose() {
	  // 可以干一些事情
	},
    handlePay() {
      console.log('handlePay')
      // 判断是否有地址
      if (!this.currentAddress.id) {
        uni.showToast({
          title: '请选择配送地址',
          icon: 'none',
        })
        return
      }
      // 判断是否有商品
      if (this.goodsList.length == 0) {
        uni.showToast({
          title: '请选择商品',
          icon: 'none',
        })
        return
      }
      this.$api
        .orderPay({
          car_ids: this.car_ids || '',
          product_id: this.product_id || '',
          buy_number: this.buy_number || '',
          order_id: this.order_id || '',
          user_address_id: this.currentAddress.id,
          remark: this.remark,
        })
        .then((res) => {
          if (res.code == 0) {
            // 发起支付
            this.pay(res.data)
            return
          } else if (res.code == -1) {
            this.$refs.stockPopup.openPopup()
		  } else if (res.code == -2) {
			  this.$refs.limitPopup.openPopup()
          } else {
            uni.showToast({
              title: res.msg,
              icon: 'none',
            })
          }
        })
    },
    pay(data) {
      console.log(data)
      wx.requestPayment({
        timeStamp: data.timeStamp,
        nonceStr: data.nonceStr,
        package: data.package,
        signType: data.signType,
        paySign: data.paySign,
        success: (res) => {
          console.log(res)
          if (res.errMsg == 'requestPayment:ok') {
            uni.showToast({
              title: '支付成功',
              icon: 'success',
            })
            uni.redirectTo({
              url:
                '/pages/settlement/status/index?status=success&order_id=' +
                data.order_id +
                '&order_no=' +
                data.order_no,
            })
          }
        },
        fail: (res) => {
          console.log(res, 'fail')
          if (res.errMsg == 'requestPayment:fail cancel') {
            uni.showToast({
              title: '支付取消',
              icon: 'none',
            })
            setTimeout(() => {
              uni.redirectTo({
                url:
                  '/pages/settlement/status/index?status=fail&order_id=' +
                  data.order_id +
                  '&order_no=' +
                  data.order_no,
              })
            }, 500)
          }
        },
      })
    },
  },
}
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
